<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>WebSocket Example</title>
<script type="text/javascript">

</script>
</head>
<body>
<h1>WebSocket Chat Example</h1>
<div id="status">Connecting...</div>
<div id="messages"></div>
<a href="#" onclick="sendMessage()">fa</a>
</body>
<script>

   if (!window.SharedWorker) {
        alert('您的浏览器不支持 SharedWorker，请使用 Chrome/Firefox/Edge');
    }

     let uuid = ''
      const worker = new SharedWorker('worker.js');
      
      // 必须调用 start() 启用通信
      worker.port.start();
      
      // 接收 WebSocket 消息
      worker.port.onmessage = (e) => {
          if(e.data.type == 'on' && e.data.data == 'ok'){
              document.getElementById('status').innerText = '登录成功.';
          }
         if(e.data.type == 'ping'){
              console.log('ping');
          }
        if(e.data.type == 'msg'){

            try {
                const data = JSON.parse(e.data.data);
                console.log(data)
                if(data.message == 'Login successful'){
                    document.getElementById('status').innerText = '登录成功.';
                }else{
                    displayNewMessage(data);
                }
    
            } catch (e) {
                console.error('解析消息失败：', e);
            }


          }
           if (e.data.type === 'connect') {
                uuid = e.data.uuid;
                alert('连接成功')
                return;
            }
            console.log('Received:', e.data);
            
        
      };
    
    
      // 发送消息到 WebSocket
      function sendMessage() {
        worker.port.postMessage('Hello from page!');
      }
      
      
    window.onbeforeunload = function(e) {
        console.log(worker);
        worker.port.postMessage({
                "type": 'close',
                "uuid": "oe"
            });
    };



    function displayNewMessage(data) {
        const messageContainer = document.getElementById('messages');
        const newMessageElement = document.createElement('div');
        newMessageElement.innerText = `New Message: ${data.message}`;
        messageContainer.appendChild(newMessageElement);
    }
    
</script>
</html>